package com.atguigu.registration.user.service.impl;

import com.atguigu.registration.common.exception.RegistrationException;
import com.atguigu.registration.common.helper.JwtHelper;
import com.atguigu.registration.common.result.ResultCodeEnum;
import com.atguigu.registration.enums.AuthStatusEnum;
import com.atguigu.registration.model.user.Patient;
import com.atguigu.registration.model.user.UserInfo;
import com.atguigu.registration.user.mapper.UserInfoMapper;
import com.atguigu.registration.user.service.PatientService;
import com.atguigu.registration.user.service.UserInfoService;
import com.atguigu.registration.vo.user.LoginVo;
import com.atguigu.registration.vo.user.UserAuthVo;
import com.atguigu.registration.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Jiang Yizhi
 * @Date: 2022/5/3 4:38 PM
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PatientService patientService;

    /** 用户手机号登录接口 */
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        /** 从loginVo里获取手机号和验证码 */
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        /** 判断得到的值是否为空，如果为空，抛出异常 */
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        /** 判断验证码是否一致，如果不一致，抛出异常*/
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new RegistrationException(ResultCodeEnum.CODE_ERROR);
        }
        /** 绑定手机号码 */
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new RegistrationException(ResultCodeEnum.DATA_ERROR);
            }
        }

        if (userInfo == null) {

            /** 判断是否第一次登录，根据手机号查询数据库 */
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {/** 第一次登录 */
                /** 添加信息到数据库 */
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }

        /**校验是否被禁用 */
        if(userInfo.getStatus() == 0) {
            throw new RegistrationException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        /** 不是第一次登录，直接登录 */
        /** 返回登录信息 */
        /** 返回用户名，token */

        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        /** 使用jwts生成token */
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        return userInfo;
    }

    /** 用户认证接口 */
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        /** 根据用户id查询查询用户信息 */
        UserInfo userInfo = baseMapper.selectById(userId);
        /** 设置认证信息 */
        /** 认证人的姓名 */
        userInfo.setName(userAuthVo.getName());
        /** 其他认证信息 */
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        /** 进行信息更新 */
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        /** UserInfoQueryVo获取条件值 */
        String name = userInfoQueryVo.getKeyword(); /** 用户名称 */
        Integer status = userInfoQueryVo.getStatus(); /** 用户状态 */
        Integer authStatus = userInfoQueryVo.getAuthStatus(); /** 认证状态 */
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        /** 对条件值进行非空判断 */
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }
        /** 调用mapper的方法 */
        Page<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    /** 用户锁定 */
    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    /** 认证审批 */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    /** 编号变成对应值封装 */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        /** 处理认证状态编码 */
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        /** 处理用户状态 */
        String statusString = userInfo.getStatus().intValue() == 0? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }




}
